package com.telsoft.hms.data;

import java.util.ArrayList;
import java.util.List;

import com.telsoft.hms.lib.admin.client.data.ClientDataPreprocessor;
import com.telsoft.hms.lib.security.exception.UserNotExistsException;
import com.telsoft.hms.lib.security.session.Session;
import com.telsoft.hms.util.SessionUtil;

public class Authorizator_DATA extends ClientDataPreprocessor {
	/**
	 * @author NinhNV
	 * @param strKey
	 *            sercurity key
	 * @param username
	 *            user đăng nhập
	 * @param objectPath
	 *            Đường dẫn chức năng
	 * @return String[] Mảng tên quyền được phép sử dụng trong chức năng (I:
	 *         insert, U: Update, D: Delete...)
	 * @throws Exception
	 *             Ngày tạo 15/09/2014
	 */
	public String[] getAuthorizator(String strKey, String objectPath)
			throws Exception {
		String hospitalKey = null;
		long userId = 0;
		List<String> listAuthorizator = new ArrayList<String>();
		String strSql = "SELECT smr.right_code, MOD (MIN (2 * child_level + access_type), 2) access_type"
				+ " FROM AM_OBJECT sm,"
				+ " (SELECT SUM.OBJECT_ID, SUM.right_code, SUM.access_type, 0 child_level"
				+ " FROM AM_USER_OBJECT SUM, AM_OBJECT_right smr"
				+ " WHERE SUM.OBJECT_ID = smr.OBJECT_ID"
				+ " AND SUM.right_code = smr.right_code"
				+ " AND SUM.user_id =  ?"
				+ " UNION ALL"
				+ " SELECT smr.OBJECT_ID, smr.right_code, smr.access_type, 1000 child_level"
				+ " FROM AM_OBJECT_right smr WHERE smr.access_type > 0"
				+ " UNION ALL"
				+ " SELECT DISTINCT sgm.OBJECT_ID, sgm.right_code, sgm.access_type, sg.child_level"
				+ " FROM AM_GROUP_OBJECT sgm, AM_OBJECT_right smr,"
				+ " (SELECT sg.GROUP_ID, LEVEL child_level"
				+ " FROM AM_GROUP sg "
				+ " WHERE NVL (status, 0) > 0"
				+ " START WITH sg.GROUP_ID IN ("
				+ " SELECT sgu.GROUP_ID FROM AM_GROUP_USER sgu"
				+ " WHERE sgu.user_id = 1)"
				+ " CONNECT BY PRIOR sg.PARENT_ID = sg.GROUP_ID) sg"
				+ " WHERE sgm.GROUP_ID = sg.GROUP_ID"
				+ " AND sgm.OBJECT_ID = smr.OBJECT_ID) smr"
				+ " WHERE sm.OBJECT_ID = smr.OBJECT_ID"
				+ " AND nvl(sm.status,0) > 0 AND sm.path = ?"
				+ " GROUP BY smr.right_code"
				+ " HAVING MOD (MIN (2 * child_level + access_type), 2) > 0";
		try {
			Session session = SessionUtil.getSession(strKey);
			hospitalKey = session.getHospitalKey();
			userId = session.getUserId();
			open(hospitalKey);
			mStmt = mConnection.prepareStatement(strSql);
			mStmt.setLong(1, userId);
			mStmt.setString(2, objectPath);

			mRs = mStmt.executeQuery();

			while (mRs.next()) {
				listAuthorizator.add(mRs.getString("RIGHT_CODE"));
			}
		} catch (Exception e) {
			throw e;
		} finally {
			close(mRs);
			close(mStmt);
			close(mConnection);
		}

		return (String[]) listAuthorizator.toArray(new String[listAuthorizator
				.size()]);
	}
}
